package org.example.springbootproject.config;

import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import java.io.IOException;

@Component
public class JwtInterceptor implements HandlerInterceptor {

    private final JwtUtil jwtUtil;

    public JwtInterceptor(JwtUtil jwtUtil) {
        this.jwtUtil = jwtUtil;
    }

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws IOException {
        String path = request.getRequestURI();

        // 放行 OPTIONS 请求（CORS 预检）
        if (request.getMethod().equals("OPTIONS")) {
            return true;
        }

        // 白名单放行
        if (isPublicPath(path)) {
            return true;
        }

        String token = extractToken(request);

        if (token == null || !jwtUtil.validateToken(token)) {
            response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "无效的 Token");
            return false;
        }

        // 获取用户角色
        String role = jwtUtil.extractRole(token);

        // 检查是否为受保护的接口
        if (isProtectedPath(path) && !role.equals("admin")) {
            // 普通用户访问受保护接口时返回空值
            response.setStatus(HttpServletResponse.SC_OK);
            response.getWriter().write("[]"); // 返回空数组或空对象
            return false;
        }

        // 刷新 token（延长有效期）
        String newToken = jwtUtil.refreshToken(token);
        if (newToken != null) {
            // 将新 token 放入响应头
            response.setHeader("Authorization", "Bearer " + newToken); // 返回新 token
        }

        return true;
    }

    private boolean isPublicPath(String path) {
        return path.equals("/api/exam/login")
                || path.equals("/api/exam/register")
                || path.equals("/api/exam/captcha");
    }

    private boolean isProtectedPath(String path) {
        return path.equals("/api/exam/users")
                || path.matches("/api/exam/users/\\d+");
    }

    private String extractToken(HttpServletRequest request) {
        String bearerToken = request.getHeader("Authorization");
        if (bearerToken != null && bearerToken.startsWith("Bearer ")) {
            return bearerToken.substring(7);
        }
        return null;
    }
}